import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: window.BASEURL || '',
  timeout: 50000 // request timeout
})

service.cancelToken = axios.CancelToken

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['accept-language'] = 'zh-Hans'

    if (store.getters.token) {
      config.headers['authorization'] = 'Bearer ' + store.getters.token
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    // console.log(error)
    // console.log(error.response)
    const errorResponse = error.response
    const { status, data } = errorResponse
    if (status === 401) {
      Message.error('您已注销，请重新登录！')
    } else {
      Message.error(data.error.message)
    }

    return Promise.reject(data)
  }
)

export default service
